<?php

namespace Home\Controller;

use Think\Controller;

class IndexController extends BaseController {

    protected $m;
    protected $appid='';
    protected $appsecret='';
    public function _initialize(){

        $info = M('wx_base')->where(['id'=>1])->find();
        $this->appid = $info['appid'];
        $this->appsecret = $info['appsecret'];

    }

    /*司机绑定首页*/

    public function index(){
       $this->display();
    }
    public function login(){
        $state = I('name').'|'.I('mobile');
        if(!I('get.code')){
            $redirect = urlencode('https://bj.d1.pg024.com/Home/index/login');
            $url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->appid."&redirect_uri=".$redirect."&response_type=code&scope=snsapi_base&state=".$state."#wechat_redirect";
            header('Location:'.$url);exit();
        }else{
            $state=I('get.state');
            $code=I('get.code');
            $result = $this->login_token($this->appid,$this->appsecret,$code);
            $data = explode('|',$state);
            $save = M('driver')->where(['realname'=>$data[0],'mobile'=>$data[1]])->save(['wx_openid'=>$result['openid']]);
            // echo M('driver')->getLastsql();die;
            if($save){
                echo "<script>alert('绑定成功，请勿重复绑定！');window.location.href='https://bj.d1.pg024.com/Home/index/index'</script>";
            }else{
                echo "<script>alert('绑定失败，请认真核对！');window.location.href='https://bj.d1.pg024.com/Home/index/index'</script>";
            }
            exit;
            // ll($data);
            // echo $code;die;
        }
    }
        //公众号登录code换取token
    public function login_token($appid,$appsecret,$code){
        $config = M('wx_login')->find();
        $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$code."&grant_type=authorization_code";
        $res = sendGet($url);
        $info = json_decode($res,true);
        $up = M('wx_login')->where('id',1)->save(['wx_token'=>$info['access_token'],'wx_time'=>time()+3600]);
        // $token = $info;
        // if($$config['wx_time']<time()){
        // }else{
        //     $token = $config['token'];
        // }
        return $info;
    }

}